import { useRouteError } from 'react-router';
import { Button, Layout, Result } from 'antd';
import { isRouteErrorResponse } from 'react-router-dom';
import { ExceptionStatusType } from 'antd/es/result';
import { isHttpException } from 'src/feature-antd/feature-error-boundary/utils.ts';

export function FeatureErrorBoundary() {
  const error = useRouteError();
  const is = isRouteErrorResponse(error);
  // SORRY, YOU DON'T HAVE PERMISSION TO ACCESS THIS PAGE. PLEASE SIGN IN.
  // SORRY, SOMETHING WENT WRONG – WE APOLOGIZE FOR ANY INCONVENIENCE.

  if (isHttpException(error)) {
    if (error.response?.status !== 200) {
      return (
        <Result
          status={error.response?.status as ExceptionStatusType}
          title={error.response.status}
          subTitle={error.response.statusText}
          extra={
            <Button
              type="primary"
              children="Back"
              onClick={() => history.back()}
            />
          }
        />
      );
    }

    return (
      <Result
        status={error.response?.data?.code}
        title={error.response?.data?.code}
        subTitle={error.response?.data?.message}
        extra={
          <Button
            type="primary"
            children="Back"
            onClick={() => history.back()}
          />
        }
      />
    );
  }

  return (
    <Layout>
      {is ? (
        <Result
          status={error.status as ExceptionStatusType}
          title={error.status}
          subTitle={error.statusText}
          extra={
            <Button
              type="primary"
              children="Back"
              onClick={() => history.back()}
            />
          }
        />
      ) : (
        <Result
          status={500}
          title={500}
          subTitle="SORRY, SOMETHING WENT WRONG – WE APOLOGIZE FOR ANY INCONVENIENCE."
        />
      )}
    </Layout>
  );
}
